const CONFIG = require("../../config")
const knex = require('knex')(CONFIG.mysql);
let saveTime = new Date().toLocaleString('chinese', { hour12: false }).replace(/\//g, "-");
let mydata = new Date();
let saveDay = mydata.getFullYear().toString() + (mydata.getMonth() + 1).toString() + mydata.getDate().toString();
let fs = require("fs");
const savefile = require("../savefile/savefile");
module.exports = {
    /*
    如何获取值 get请求方法   获取req的query方法取值
               post请求方法  获取req的body方法取值
    */

    async getList(req, res) {
        //获取url值
        const { current, size, category } = req.query;
        let data;
        let total;
        knex('blade_visual').select().where({ category: category }).then(resp => {
            total = resp.length;
            data = resp.slice((current - 1) * 10, current * size);
        }).then(() => {
            if (data.length >= 0) {
                items = {
                    code: 200,
                    data: {
                        current: current,
                        hitCount: false,
                        orders: [],
                        pages: 1,
                        records: data,
                        searchCount: true,
                        size: size,
                        total: total
                    },
                    msg: "操作成功",
                    success: true
                }
                res.send(items)
            } else {
                res.send("error");
            }
        })
    },

    async getDetail(req, res) {
        const { id } = req.query;
        let data;
        knex('blade_visual_config').select().where({ visual_id: id }).then(resp => {
            data = {
                config: {
                    component: resp[0].component,
                    detail: resp[0].detail,
                    id: resp[0].id,
                    visualId: resp[0].visual_id
                },
                visual: {
                    category: 1,
                    createDept: -1,
                    createTime: 1
                },
                msg: resp[0].msg,
                success: resp[0].success
            };
        }).then(() => {
            if (data) {
                items = {
                    code: 200,
                    data: data,
                    msg: "操作成功",
                    success: true
                }
                res.send(items)
            } else {
                res.send("error");
            }
        })
    },

    async postSave(req, res) {
        let { category, password, title } = req.body.visual;
        let { detail, component } = req.body.config;
        knex('blade_visual').insert({ category: category, password: password, title: title, status: 1, is_deleted: 1, create_time: saveTime }).then(resp => {
                if (resp) {
                    //操作config表，为其添加数据
                    knex('blade_visual_config').insert({ visual_id: resp, detail: detail, component: component }).then(() => {
                        res.send({
                            code: 200,
                            msg: "操作成功",
                            success: true
                        })
                    })
                } else {
                    res.send({
                        code: 4001,
                        msg: "操作失败",
                        success: true
                    })
                }
            })
            //res.send('postUpdate');
    },

    async postUpdate(req, res) {
        //console.log("req.body-----", req.body)
        let { category, password, id, title, status, backgroundUrl } = req.body.visual
        let visualId = 0
        let detail = ""
        let component = ""
        if (req.body.config) {
            visualId = req.body.config.visualId;
            detail = req.body.config.detail
            component = req.body.config.component
        }
        //console.log("req.body.config------", req.body.config);
        await knex('blade_visual').update({ background_url: backgroundUrl, category: category, password: password, title: title, status: status, update_time: saveTime }).where({ id: id });
        knex('blade_visual_config').update({ detail: detail, component: component }).where({ visual_id: visualId })
            .then(resp => {
                if (resp === 1) {
                    res.send({
                        code: 200,
                        msg: "操作成功",
                        success: true
                    })
                } else {
                    res.send({
                        code: 4001,
                        msg: "操作失败",
                        success: true
                    })
                }
            })
    },

    async postRemove(req, res) {
        console.log("res._parsedUrl", req.query.ids);
        const ids = req.query.ids;
        knex('blade_visual').delete().where({ id: ids }).then(resp => {
            if (resp) {
                knex('blade_visual_config').delete().where({ visual_id: ids }).then(() => {
                    res.send({
                        code: 200,
                        msg: "操作成功",
                        success: true
                    })
                })
            } else {
                res.send({
                    code: 4001,
                    msg: "操作失败",
                    success: true
                })
            }
        })
    },
    async postCopy(req, res) {
        const id = req.query.id;
        let data;
        knex('blade_visual').select().where({ id: id }).then(resp => {
            //console.log(resp[0])
            data = resp[0];
        }).then(() => {
            //blade_visualf
            knex('blade_visual').insert({ title: data.title, background_url: data.background_url, category: data.category, password: data.password, create_time: data.create_time, status: data.status, is_deleted: data.is_deleted }).then(resCopyId => {
                //搜索原来的config里面的数据
                knex('blade_visual_config').select().where({ visual_id: id }).then(resdata => {
                    //为复制的模板插入新的config数据
                    // console.log("````````````data`````````", resdata)
                    knex('blade_visual_config').insert({ visual_id: resCopyId, detail: resdata[0].detail, component: resdata[0].component }).then(() => {
                        if (resdata) {
                            res.send({
                                code: 200,
                                msg: "操作成功",
                                success: true
                            })
                        } else {
                            res.send({
                                code: 4001,
                                msg: "操作失败",
                                success: true
                            })
                        }
                    })
                })
            })
        })
    },

    async buildExists(req, res, next) {
        //判断是否有文件夹，有true,无false
        fs.exists('@/../uploads/' + saveDay, function(exists) {
            if (exists) {
                console.log("true");
            } else {
                fs.mkdir('@/../uploads/' + saveDay, function(err) {
                    if (err) {
                        console.log(err);
                    }
                    console.log("success")
                })
            }
            next();
        })
    },
    async ceshi(req, res, next) {
        const save = require("../../controller/savefile/savefile");
        console.log("----save.savefile-----", save.savefile())
        next()
    },
    async postPutFile(req, res) {
        /*
        1.在uploads下生成现在日期的文件夹
        2.判断是否有该文件夹，没有创建  ， 有在该文件夹下生成图片
        */
        console.log("-----saveDay---", saveDay)
        const file = req.file;
        //file.url = `http://localhost:3002/uploads/${saveDay}/${file.filename}`
        file.url = `/uploads/${saveDay}/${file.filename}`
        res.send({
            data: file,
            code: 200,
            msg: "操作成功",
            success: true
        });
    },
    async postPutFileImg(req, res) {
        console.log("-----req-----", req.query.isImg)
        const file = req.file;
        if (req.query.isImg == "ImgBg") {
            file.url = `${CONFIG.fileBg}${file.filename}`
        } else if (req.query.isImg == "Image") {
            file.url = `${CONFIG.fileSource}${file.filename}`
        } else if (req.query.isImg == "Border") {
            file.url = `${CONFIG.fileBorder}${file.filename}`
        }
        res.send({
            data: file,
            code: 200,
            msg: "操作成功",
            success: true
        });
    },
}